Trulli
www.rstudio.com

Overview

By the end of this practical you will know how to:

  1. Create a new R Markdown file (.Rmd)
  2. “Knit” an R Markdown file to an .html or .pdf report
  3. Format text using formatting tags
  4. Create code chunks
  5. Include code output in sentences with inline chunks

Packages

Package Installation
tidyverse install.packages("tidyverse")
knitr install.packages("knitr")
DT install.packages("DT")
broom install.packages("broom")
rmdformats install.packages("rmdformats")
xaringan install.packages("xaringan")

Cheatsheet

Datasets

File Rows Columns
mcdonalds.csv 260 24

Tasks

A - Setup

  1. Open your R project. It should already have the folders 0_Data and 1_Code. Make sure that the data files listed in the Datasets section above are in your 1_Data folder

  2. Because R Markdown looks quite a bit different from standard R code, the best way to look at examples is to see a new R Markdown document in action. In RStudio, click File – New File – R Markdown

  1. Give the document a title and an author. For the output format, select HTML (the default). Click Ok!

  1. A new file that looks like this should open up. This is your first R Markdown document!

  1. Save your markdown file in your main project directory (not in the 4_Markdown folder! – you’ll put it there later!) under the name mcdonalds.Rmd

  2. Now knit your document to an HTML file. To do this, click the knit button (or use the Command + Shift + K shortcut)

  1. Now you should see your final, HTML document! Scroll up and down the document and see how she looks!

B - Load packages, data and set default chunk options

  1. You should always start your markdown file by loading packages and data in a code chunk. We’ll do this inside of the first chunk with the setup label. Inside of this chunk, write the comment # Load Packages -------------. Then, using the library() function, load the packages listed in the Packages section above.

  1. Knit your document! Make sure you don’t get any errors!

  2. Now it’s time to load your datafiles. In the same setup chunk, load each of the data files listed in the Datasets section.

# --- Load packages
library(XX)
library(XX)

# --- Load data
XXX <- read_csv()
XXX <- read_csv()
  1. Knit your document! Make sure you don’t get any errors!

  2. Now it’s time to change some of the default chunk options. In your setup chunk, change the existing values of knitr::opts_chunk$set to the following:

# INCLUDE ALL OF THIS CODE IN YOUR FIRST CHUNK!

knitr::opts_chunk$set(fig.width = 6,        # Figure width (in)
                      fig.height = 4,       # Figure height (in)
                      echo = FALSE,          # Repeat code
                      eval = TRUE,          # Evaluate chunks
                      message = FALSE,      # Don't print messages
                      warning = FALSE,      # Don't print warnings
                      fig.align = 'center') # Center figures

options(digits = 2)  # Round all output to 2 digits
  1. Knit your document! Make sure you see an output!

C - Add formatted text

  1. Below your last markdown chunk, write the necessary text and Markdown tags to create the following sentence. Be sure to create italic and bold text using the proper formatting tags!
  1. Create a new first level header with the text “McDonalds” using a single hashtag

  2. Knit the document!

  3. You can find the McDonalds logo on wikipedia at the following link: https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/McDonald%27s_Golden_Arches.svg/2000px-McDonald%27s_Golden_Arches.svg.png. Using the include_graphics() function, include this image in your document (To make the image a bit smaller, include the chunk argument out.width = "30%")

include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/McDonald%27s_Golden_Arches.svg/2000px-McDonald%27s_Golden_Arches.svg.png")
  1. Include the appropriate text and formatting to write the following sentence. When writing the number of columns and rows, use in-line chunks to get the data directly from the mcdonalds object! You can get the number of columns with ncol(mcdonalds) and the number of rows with nrow(mcdonalds)

D - Add a formatted table with datatable()

  1. Create a new code chunk by either clicking the “Insert - R” button, or by using the “Command + Option + I”" shortcut on Mac

  2. Inside the chunk, include the following code which uses the datatable function to render a dataframe as a nicely formatted HTML table.

datatable(mcdonalds %>% select(1:6))
  1. Knit the document! Do you see your nicely formatted table?

E - Add plots

  1. Write the appropriate combination of markdown, text, and code to create the following output (Here’s some ggplot2 code that might help!)

ggplot(data = mcdonalds,
       aes(x = XX)) +
  geom_histogram(col = "white") +
  labs(title = "XX",
       subtitle = "XX",
       caption = "XX") +
  theme_bw()
  1. Knit the document! Diagnose and correct any errors!

  2. Write the appropriate combination of markdown, text, and code to create the following output (Here’s some ggplot2 code that might help!):

ggplot(data = XX,
       aes(x = XX, y = XX)) +
  geom_point() +
  labs(title = "XX",
       subtitle = "XX",
       caption = "XX") +
  theme_bw()
  1. Knit the document! Diagnose and correct any errors!

F - Add a table of statistical test results

Now let’s show the results of a regression analysis predicting the sodium content of an item as a function of its calories.

  1. Create a new code chunk. Inside of the chunk, create an object called cal_sod_lm that is the result of a regression analysis predicting Sodium as a function of Calories. Use the following template
# Create regression model predicting Sodium from Calories

cal_sod_lm <- lm(formula = XX ~ XX,
                 data = mcdonalds)
  1. Now, using the following template for help, write the appropirate text / code to create the following output.
# Export cal_sod_lm to a nicely formatted table

kable(x = tidy(cal_sod_lm), 
      digits = 3, 
      caption = "Regression analysis predicting Sodium from Calories")

  1. Knit the document! Diagnose and correct any errors!

G - Keep going!

  1. Add the appropriate code to add the following output.

ggplot(data = mcdonalds,
       aes(x = XX, y = XX, fill = XX)) +
  stat_summary(geom = "bar", fun.y = "mean") +
  guides(fill = FALSE) +
  labs(title = "McDonalds Menu Items",
       subtitle = "Created with ggplot2",
       caption = "Source: Kaggle.com") +
  theme_bw()
  1. Knit the document! Diagnose and correct any errors!

  2. Add the appropriate code to add the following output.

Calories_agg <- XX %>%
  group_by(XX) %>%
  summarise(
    Min = min(Calories),
    Mean = mean(Calories),
    Median = median(Calories),
    Max = max(Calories)
  )

kable(x = XX, 
      caption = "XX")
  1. Knit the document! Diagnose and correct any errors!

G - Managing working directories with Markdown

  1. Now it’s time to move your Markdown file to your 4_Markdown folder. Move your speffanalysis.Rmd file to your 4_Markdown folder using your computer file browser (Finder on Mac, Windows explorer on PC). Now, try knitting your document. You should get an error! What happened?!

  2. The problem is that when you knit your Markdown file, R changes your working directory to the folder where your markdown file is located. However, now that you moved your file to your 4_Markdown folder, this isn’t true anymore. You need to tell Markdown that the root directory of your project is one directory up! Thankfully this is easy to do. Just add the following code to your initial setup R chunk:

# Tell R Markdown that the root directory is now one folder
#   up from the folder the markdown file is in

knitr::opts_knit$set(root.dir = "../")
  1. Knit your document! Did everything work? If not, try to correct the working directory issues. Don’t be afraid to ask for help!

X - Add results from the happiness survey

  1. If you have LaTex installed on your computer, try knitting your document to PDF format by clicking the Knit button and knit to PDF. If you don’t have LaTeX installed, don’t worry :)

Other Markdown templates

  1. Don’t like the standard markdown template? You can get many other templates from the rmdformats package. Install the package with rmdformats. Then create a new markdown file from one of the temples with File – New File – R Markdown – From Template. Try the HTML readthedown template. Knit the document and see how it looks different from your standard template.

Slideshow

  1. Now it’s time to create a slideshow! To do this, we’ll use the Ninja template (click here for a demo) from the xaringan package (that’s what we use for all of our BaselRBootcamp slides). Install the xaringan package by running install.packages('xaringan')

  2. Once you’ve installed xaringan, open a new template with File – New File – R Markdown – From Template – Ninja Presentation. Give the presentation a title and your name as the author. Then click ok.

  3. You should see a new .Rmd document open. Save the document in your main project directory as slideshow.Rmd.

  4. Knit the document to see the outline of the presentation!

  5. Play around with the presentation a bit. Change the existing content a bit and add a few slides. Try adding an image (maybe this one: https://actgnetwork.org/sites/all/themes/actg/images/actg_logo_275.png) by saving the image to your 0_Materials folder, and then loading the image into your document with include_graphics().

  6. Now, try to customize the presentation to include all of main analyses, outputs, and plots you have in your speffanalysis.Rmd document! Of course, there won’t be room for all of the text, so treat it like a normal presentation and put in what’s important.